手寫辨識是最基本入門款,利用第22天canvas手勢繪圖和參照tensorflow 的codelab,來玩手寫辨識。
將 TensorFlow Lite 模型添加到assets文件夾
mnist.tflite
build.gradle(app)
dependencies {
implementation 'org.tensorflow:tensorflow-lite:2.5.0'
}
android {
...
aaptOptions {
noCompress "tflite"
}
...
}
建立和初始化 DigitClassifier (TensorFlow Lite interpreter)
class DigitClassifier(private val context: Context) {
….
private fun initializeInterpreter() {
//載入tensorflow lite 模組
val assetManager = context.assets
val model = loadModelFile(assetManager)
// 初始化 TF Lite 解釋器 和 開啟神經網路
val options = Interpreter.Options()
options.setUseNNAPI(true)
val interpreter = Interpreter(model, options)
// 模型中讀取模型輸入格式
val inputShape = interpreter.getInputTensor(0).shape()
inputImageWidth = inputShape[1]
inputImageHeight = inputShape[2]
modelInputSize = FLOAT_TYPE_SIZE * inputImageWidth * inputImageHeight * PIXEL_SIZE
// 完成初始化
this.interpreter = interpreter
isInitialized = true
}
….
}
輸入資料給模型預測
private fun classify(bitmap: Bitmap): String {
…
// … 先處理輸入的圖片
val resizedImage = Bitmap.createScaledBitmap(bitmap, inputImageWidth, inputImageHeight, true)
val byteBuffer = convertBitmapToByteBuffer(resizedImage)
…
val result = Array(1) { FloatArray(OUTPUT_CLASSES_COUNT) }
interpreter?.run(byteBuffer, result)
…
//最後輸出文字結果
return getOutputString(result[0])
}
觸控手勢處劃完後放開呼叫 classifyDrawing(extraBitmap)
override fun onTouchEvent(event: MotionEvent): Boolean {
motionTouchEventX = event.x
motionTouchEventY = event.y
when (event.action) {
MotionEvent.ACTION_DOWN -> touchStart()
MotionEvent.ACTION_MOVE -> touchMove()
MotionEvent.ACTION_UP -> classifyDrawing(extraBitmap)
}
return true
}
執行結果:
https://developer.android.com/codelabs/digit-classifier-tflite